using MultiAgentsClient.ChatDataStructures;
using MultiAgentsClient.Manager.DataModel;
using MultiAgentsClient.Service.SignalRService;

using ApiRequestType = MultiAgentsClient.Service.SignalRService.SignalRWorkflowService.ApiRequestType;

namespace MultiAgentsClient.Manager;

public class SystematicNotificationManager : ManagerBase
{
    private readonly SignalRWorkflowService signalRWorkflowService;

    private readonly SystematicNotificationDataModel systematicNotificationDataModel;
    private readonly SystemConfigDataModel systemConfigDataModel;
    private readonly UserDataModel userDataModel;

    #region events
    // recieve command from UI
    public record NotificationProccessedCommand(int NotificationId);

    // recieve command from signalR
    public record RecieveSystematicNotificationCommand(List<WorkflowNotification> Notifications);

    // send command to UI
    public record RecieveSystematicNotificationEvent(List<WorkflowNotification> Notifications);
    #endregion

    public SystematicNotificationManager(
        SignalRWorkflowService signalRWorkflowService,
        SystematicNotificationDataModel systematicNotificationDataModel,
        SystemConfigDataModel systemConfigDataModel,
        UserDataModel userDataModel)
    {
        this.signalRWorkflowService = signalRWorkflowService;
        this.systematicNotificationDataModel = systematicNotificationDataModel;
        this.systemConfigDataModel = systemConfigDataModel;
        this.userDataModel = userDataModel;
        eventBus.Subscribe<NotificationProccessedCommand>(cmd => { Task.Run(() => NotificationProccessedCommandHandler(cmd)); });

        eventBus.Subscribe<RecieveSystematicNotificationCommand>(cmd => { Task.Run(() => RecieveSystematicNotificationCommandHandler(cmd)); });
    }

    #region request
    private async Task NotificationProccessedCommandHandler(NotificationProccessedCommand cmd)
    {
        await signalRWorkflowService.SendSignalRRequest(ApiRequestType.WorkflowProccessedRequest.ToString(), new Dictionary<string, object>()
            {
                { "sessionId", systemConfigDataModel.sessionId},
                { "userId", userDataModel.Id },
                { "notificationId", cmd.NotificationId },
            });
    }
    #endregion


    #region response
    private void RecieveSystematicNotificationCommandHandler(RecieveSystematicNotificationCommand notificationCmd)
    {
        foreach (WorkflowNotification notification in notificationCmd.Notifications)
        {
            systematicNotificationDataModel.notificationList.Add(notification);
        }

        eventBus.Publish(new RecieveSystematicNotificationEvent(notificationCmd.Notifications));
    }
    #endregion
}
